<script setup>
import { useMessage, NCard, darkTheme, NButton, NImage, NModal, NTime, NInput, NInputGroup } from 'naive-ui'
import { useStore } from '@/stores/index'
import axios from 'axios'
import { ref } from 'vue'

const message = useMessage() // 实例化信息条
const store = useStore() // 实例化useStore
const backedHost = store.$state.backedHost // 后端API前缀

const showAvatarModal = ref(false)  // 是否显示修改头像模态框
const showPasswordModal = ref(false)  // 是否显示修改密码模态框
const showEmailModal = ref(false)  // 是否显示修改邮箱模态框

const verifyCount = ref('获取验证码')  // 验证码倒计时
const emailVerifyCode = ref('')  // 邮箱验证码
const verifyCodeBtnStatus = ref(false)  // 验证码按钮状态

const userData = ref(store.$state.userInfo)  // 用户数据
const avatarUrl = ref('')  // 用户头像URL
const oldPassword = ref('')  // 旧密码
const newPassword = ref('')  // 新密码

// 修改用户头像
function changeAvatar() {
  if (!avatarUrl.value) {
    message.warning('头像URL不能为空！')
    return null
  }
  const fetchConfig = {
    method: 'post',
    headers: { Authorization: 'Bearer ' + localStorage.getItem('token') },
    url: backedHost + '/user/change_avatar?avatarUrl=' + avatarUrl.value
  }
  axios(fetchConfig)
    .then((response) => {
      if (response.data.code === 2000) {
        message.success('修改头像成功！')
        setTimeout(() => {
          window.location.reload()
        }, 800)
      } else {
        message.warning('修改头像失败，请稍后再试！')
      }
    })
    .catch((error) => {
      console.log(error)
      message.warning(error.response.data.message)
    })
}

// 修改用户昵称
function changeNickname() {
  if (!userData.value.nickname) {
    message.warning('昵称不能为空！')
    return null
  }
  const fetchConfig = {
    method: 'post',
    headers: { Authorization: 'Bearer ' + localStorage.getItem('token') },
    url: backedHost + '/user/change_nickname?nickname=' + userData.value.nickname
  }
  axios(fetchConfig)
    .then((response) => {
      if (response.data.code === 2000) {
        message.success('修改昵称成功！')
        setTimeout(() => {
          window.location.reload()
        }, 800)
      } else {
        message.warning('修改昵称失败，请稍后再试！')
      }
    })
    .catch((error) => {
      console.log(error)
      message.warning(error.response.data.message)
    })
}

// 修改用户密码
function changePassword() {
  if (!oldPassword.value || !newPassword.value) {
    message.warning('密码不能为空！')
    return null
  }
  const fetchConfig = {
    method: 'post',
    headers: { Authorization: 'Bearer ' + localStorage.getItem('token') },
    url: backedHost + '/user/change_password?old_password=' + oldPassword.value + "&new_password=" + newPassword.value
  }
  axios(fetchConfig)
    .then((response) => {
      if (response.data.code === 2000) {
        message.success('修改密码成功！')
        setTimeout(() => {logout()}, 800)  // 登出
      } else {
        message.warning('修改密码失败，请稍后再试！')
      }
    })
    .catch((error) => {
      console.log(error)
      message.warning(error.response.data.message)
    })
}

// 登出
function logout() {
  const fetchConfig = {
    method: 'post',
    headers: { Authorization: 'Bearer ' + localStorage.getItem('token') },
    url: backedHost + '/user/logout'
  }
  axios(fetchConfig)
    .then((response) => {
      if (response.data.code === 2000) {
        message.warning('退出登录成功！')
        localStorage.removeItem('token')
        setTimeout(() => {
          window.location.href = '/'
        }, 800)
      } else {
        message.warning('退出登录失败，请稍后再试！')        
        setTimeout(() => {
          window.location.href = '/'
        }, 800)
      }
    })
    .catch((error) => {
      console.log(error)
      message.warning(error.response.data.message)
    })
}

// 获取邮箱验证码
function getEmailVerifyCode() {
  if (!userData.value.email) {
    message.warning('邮箱不能为空！')
    return null
  }
  verifyCodeBtnStatus.value = true  // 禁用按钮
  verifyCount.value = '请求中...'
  const fetchConfig = {
    method: 'post',
    headers: { Authorization: 'Bearer ' + localStorage.getItem('token') },
    url: backedHost + '/verification_code?email=' + userData.value.email
  }
  axios(fetchConfig)
    .then((response) => {
      if (response.data.code === 2000) {
        message.warning('发送验证码成功，请查收邮箱，5分钟内有效！', {duration: 5000})
        verifyCount.value = 60
        sessionStorage.setItem('verifyCount', verifyCount.value)
        countdownVerifyCount()
      } else {
        message.warning('发送验证码失败，请稍后再试！')
      }
    })
    .catch((error) => {
      console.log(error)
      message.warning(error.response.data.message)
    })
}

// 修改用户邮箱
function changeEmail() {
  if (!userData.value.email || !emailVerifyCode.value) {
    message.warning('邮箱或验证码不能为空！')
    return null
  }
  const fetchConfig = {
    method: 'post',
    headers: { Authorization: 'Bearer ' + localStorage.getItem('token') },
    url: backedHost + '/user/change_email?email=' + userData.value.email + "&valid_code=" + emailVerifyCode.value
  }
  axios(fetchConfig)
    .then((response) => {
      if (response.data.code === 2000) {
        message.warning('修改邮箱成功！')
        // 重置验证码倒计时
        sessionStorage.setItem('verifyCount', '获取验证码')
        setTimeout(() => {
          window.location.reload()
        }, 800)
      } else {
        message.warning('修改邮箱失败，请稍后再试！')
      }
    })
    .catch((error) => {
      console.log(error)
      message.warning(error.response.data.message)
    })
}

// 验证码倒计时
function countdownVerifyCount() {
  verifyCount.value = sessionStorage.getItem('verifyCount')
  if (verifyCount.value !== '获取验证码') {
    verifyCodeBtnStatus.value = true  // 禁用按钮
    const intervalId = setInterval(() => {
      verifyCount.value -= 1
      sessionStorage.setItem('verifyCount', verifyCount.value)
      if (verifyCount.value <= 0) {
        verifyCount.value = '获取验证码'
        verifyCodeBtnStatus.value = false
        clearInterval(intervalId)
      }
    }, 1000)
  }
}

// 开局计算倒计时
countdownVerifyCount()
// 获取当前用户信息
if (store.$state.userInfo === null) {
  message.warning('请先登录')
  setTimeout(() => {
    location.href = "/login"
  }, 1500)
} else {
  userData.value = store.$state.userInfo
}
</script>

<template>
  <div id="info">
    <n-card :segmented="{content: true, footer: 'soft'}" id="info-card" content-class="info-card-content" header-class="info-card-header">
      <template #header>
        <n-image :src="userData.avatar" alt="avatar" style="width: 50px;"/>
      </template>
      <template #header-extra>
        <n-button type="info" @click="showAvatarModal = true">修改头像</n-button>
        <n-modal v-model:show="showAvatarModal">
          <n-card style="width: 80%" title="修改头像" :bordered="false" role="dialog" aria-modal="true" :theme="darkTheme">
            <n-input-group class="info-group">
              <n-input v-model:value="avatarUrl" type="text" placeholder="网络图片的URL地址" clearable :theme="darkTheme"/>
              <n-button type="info" @click="changeAvatar()" :theme="darkTheme">修改</n-button>
            </n-input-group>
          </n-card>
        </n-modal>
      </template>
      <n-input-group>
        <n-button color="#3D3B40">用户名</n-button>
        <n-input type="text" :placeholder="userData.username" disabled/>
      </n-input-group>
      <n-input-group class="info-group">
        <n-button color="#3D3B40">昵称</n-button>
        <n-input :maxlength="16" v-model:value="userData.nickname" type="text" :placeholder="userData.nickname"/>
        <n-button type="info" @click="changeNickname()">修改</n-button>
      </n-input-group>
      <n-input-group class="info-group">
        <n-button color="#3D3B40">密码</n-button>
        <n-input type="text" placeholder="********" disabled/>
        <n-button type="info" @click="showPasswordModal = true">修改</n-button>
        <n-modal v-model:show="showPasswordModal">
          <n-card style="width: 80%" title="修改密码" :bordered="false" role="dialog" aria-modal="true" :theme="darkTheme">
            <n-input :maxlength="32" style="margin-top: 10px;" v-model:value="oldPassword" type="password" placeholder="老密码" :theme="darkTheme"/>
            <n-input :maxlength="32" style="margin-top: 10px;" v-model:value="newPassword" type="password" placeholder="新密码" :theme="darkTheme"/>
            <n-button style="width: 100%;margin-top: 10px;" type="info" @click="changePassword()" :theme="darkTheme">修改</n-button>
          </n-card>
        </n-modal>
      </n-input-group>
      <n-input-group class="info-group">
        <n-button color="#3D3B40">邮箱</n-button>
        <n-input type="text" :placeholder="userData.email" disabled/>
        <n-button type="info" @click="showEmailModal = true">修改</n-button>
        <n-modal v-model:show="showEmailModal">
          <n-card style="width: 80%" title="修改邮箱" :bordered="false" role="dialog" aria-modal="true" :theme="darkTheme">
            <n-input-group class="info-group">
              <n-input :maxlength="32" v-model:value="userData.email" type="text" placeholder="邮箱" :theme="darkTheme"/>
              <n-button type="info" @click="getEmailVerifyCode()" :disabled="verifyCodeBtnStatus" :theme="darkTheme">{{ verifyCount }}</n-button>
            </n-input-group>
            <n-input :maxlength="6" style="margin-top: 10px;" v-model:value="emailVerifyCode" type="text" placeholder="验证码" :theme="darkTheme"/>
            <n-button style="width: 100%;margin-top: 10px;" type="info" @click="changeEmail()" :theme="darkTheme">修改</n-button>
          </n-card>
        </n-modal>
      </n-input-group>
      <n-input-group class="info-group">
        <n-button color="#3D3B40">生日</n-button>
        <n-button color="#3D3B40" ghost disabled>
          <n-time :time="userData.birthday" format="yyyy-MM-dd" unix />
        </n-button>
      </n-input-group>
      <n-button style="width: 100%;margin-top: 10px;" color="#9E1A1A" @click="logout()">登出</n-button>
    </n-card>
  </div>
</template>

<style>
#info {
  padding: 20px;
  text-align: left;
}
.info-group {
  margin-top: 10px;
}
.info-card-header {
  background-color: #F6F5F5;
  color: black;
}
.info-card-content {
  background-color: #F6F5F5;
  color: black;
}
#info-card {
  box-shadow: 0px 0px 4px 4px rgba(0, 0, 0, 0.2);
}
.info-input {
  text-align: left;
}
</style>
